import { Dialog, Loading, Message, Tree } from '@alifd/next';
import { useRequest } from 'ice';
import { useEffect } from 'react';
import { TreeDataSource } from '../entity';
import { queryRoleAuth, saveRoleAuth, SaveRoleAuthParam } from '../services';
import uniq from 'lodash/uniq';

interface Props {
  visible?: boolean;
  onClose?: () => any;
  treeData?: TreeDataSource[];
  roleId?: number;
}

function AuthorizeDialog({ visible, onClose, treeData, roleId = -1 }: Props) {
  const {
    data = [],
    request,
    loading,
    mutate,
  } = useRequest<number[], number[]>(queryRoleAuth, {
    defaultLoading: true,
  });
  const { request: saveAuth, loading: saveLoading } = useRequest<any, SaveRoleAuthParam[]>(saveRoleAuth, {
    onSuccess: () => {
      Message.success('授权成功');
      onClose?.();
    },
  });

  useEffect(() => {
    if (visible) {
      request(roleId);
    }
  }, [visible]);

  const onCheck = (keys: string[], _) => {
    const _keys = keys.map((t) => Number(t));
    mutate([...data, ..._keys]);
  };

  return (
    <Dialog
      title="角色资源授权"
      v2
      visible={visible}
      overflowScroll
      width="60%"
      onClose={onClose}
      afterClose={() => mutate([])}
      onOk={() => saveAuth({ roleId, privilegeIds: uniq(data) })}
      okProps={{ loading: saveLoading }}
      cancelProps={{ loading: saveLoading }}
    >
      <Loading visible={loading} tip="加载中..." style={{ display: 'block' }}>
        <Tree
          checkable
          showLine
          checkedKeys={uniq(data).map((t) => `${t}`)}
          checkedStrategy="all"
          selectable={false}
          defaultCheckedKeys={[]}
          onCheck={onCheck}
          dataSource={treeData}
        />
      </Loading>
    </Dialog>
  );
}

export default AuthorizeDialog;
